package com.demo.datastructure.binarySearch;

/**
 * @author ljr
 * @version 1.0
 * @description: 查找第一个值等于给定值的元素
 * @date 2021/10/13 17:25
 */
public class BinarySearch13 {

    public static int bsearch(int[] nums, int target) {
        int low = 0;
        int high = nums.length-1;
        while(low <= high){
            int mid = low+(high-low >> 1);
            if(nums[mid] > target){
                high = mid-1;
            }else if(nums[mid] < target){
                low = mid+1;
            }else{
                if(mid != 0 && nums[mid-1] != target) return mid;
                else high = mid -1;
            }
        }
        return -1;
    }

    public static int bsearch2(int[] nums, int target) {
        int low = 0;
        int high = nums.length-1;
        while(low <= high){
            int mid = low+((high-low) >> 1);
            if(nums[mid] >= target){
                high = mid-1;
            }else{
                low = mid+1;
            }
        }
        if(low < nums.length && nums[low] == target) return low;
        else return -1;
    }






    public static void main(String[] args) {
        //int[] nums = new int[]{1,3,5};
        int[] nums = new int[]{0,1,2,4,5,5,5,6,7};
        int index = BinarySearch13.bsearch(nums,5);
        System.out.println(index);
    }

}
